package cn.wowjoy.office.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.wowjoy.office.BuildConfig;

/**
 * Created by 84429 on 2017/3/22.
 */

public class CommonUtils {
    static int resID;

    public static <A, B> B modelA2B(A modelA, Class<B> bClass) {
        try {
            Gson gson = new Gson();
            B instanceB = gson.fromJson(gson.toJson(modelA), bClass);
            return instanceB;
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean isNum(String data) {
        Pattern pattern = Pattern.compile("[0-9]*");
        if (pattern.matcher(data).matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 关闭Android导航栏，实现全屏
     */
    public static void closeBar() {
        try {
            String command;
            command = "LD_LIBRARY_PATH=/vendor/lib:/system/lib service call activity 42 s16 com.android.systemui";
            ArrayList<String> envlist = new ArrayList<String>();
            Map<String, String> env = System.getenv();
            for (String envName : env.keySet()) {
                envlist.add(envName + "=" + env.get(envName));
            }
            String[] envp = envlist.toArray(new String[0]);
            Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", command}, envp);
            proc.waitFor();
        } catch (Exception ex) {
        }
    }

    /**
     * 显示导航栏
     */
    public static void showBar() {
        try {
            String command;
            command = "LD_LIBRARY_PATH=/vendor/lib:/system/lib am startservice -n com.android.systemui/.SystemUIService";
            ArrayList<String> envlist = new ArrayList<String>();
            Map<String, String> env = System.getenv();
            for (String envName : env.keySet()) {
                envlist.add(envName + "=" + env.get(envName));
            }
            String[] envp = envlist.toArray(new String[0]);
            Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", command}, envp);
            proc.waitFor();
        } catch (Exception e) {
        }
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String readStreamToString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        String result = byteArrayOutputStream.toString();
        inputStream.close();
        byteArrayOutputStream.close();
        return result;
    }

    public static String getIntegerString(String a) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(a);
        return m.replaceAll("").trim();
    }

    public static MediaPlayer playMusic(Context ct, int filename, boolean isLoop) {
        MediaPlayer mediaPlayer = MediaPlayer.create(ct, filename);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setVolume(1.0f, 1.0f);
        mediaPlayer.setLooping(isLoop);
        mediaPlayer.setOnCompletionListener(mp -> {
            if (!isLoop) {
                mp.stop();
                mp.release();
            }
        });
        mediaPlayer.start();
        return mediaPlayer;
    }

//    public static int playsound(Context ct, int res, int loop) {
//        if (MyApplication.sp == null) {
//            AudioAttributes aab = new AudioAttributes.Builder()
//                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
//                    .setUsage(AudioAttributes.USAGE_MEDIA)
//                    .build();
//            MyApplication.sp = new SoundPool.Builder().setAudioAttributes(aab).setMaxStreams(4).build();
//        }
//
//        MyApplication.sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
//            @Override
//            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
//                resID = soundPool.play(sampleId, 1, 1, 1, loop, 1);
//            }
//        });
//        MyApplication.sp.load(ct, res, 1);
//        return resID;
//    }

    public static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }
}
